<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2019/3/7
 * Time: 10:20
 */

namespace app\admin\controller;
use app\admin\model\Admin;
use app\admin\model\Role;
use app\admin\model\Rule;
use app\admin\model\Admin_role;
use think\Controller;
use think\Request;
use app\admin\model\RoleRule;
use think\Db;

class Rbac extends Controller{
    protected $admin;
    protected $request;
    protected $role;
    protected $Rule;
    protected $role_rule;
    protected $admin_role;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->admin = new Admin();
        $this->request = Request::instance();
        $this->role = new Role();
        $this->Rule = new Rule();
        $this->role_rule = new RoleRule();
        $this->admin_role=new Admin_role();
    }
    /**
     * 展示管理员列表
     */
    public function administrator()
    {
        //获取用户提交的搜索关键词
        //如果变量username 有值，则使用这个值，如果没值，则使用第二个参数提供的默认值
        $username = input('username','');
        $status = input('status',-1);
        $where = [];
        if ($username != "") {
            $where['username'] = $username;
        }
        if ($status > -1) {
            $where['status'] = $status;
        }
        $data = $this->admin->pageData($where);
        //分配用户的搜索i关键词到模板中
        $this->assign("username", $username);
        $this->assign("status", $status);

        $this->assign("admin", $data);
        return $this->fetch();
    }
    public function addAdministrator(){
        $request=Request::instance();
        if($request->isGet()){
            return $this->fetch();
        }else{
            $username=input('username');
            $password=input('password');
            $status=input('status');
            $salt=getRanKey();
            $data=['username'=>$username,"password"=>md5(md5($password).$salt),
                'salt'=>$salt,'status'=>$status,'login_ip'=>$request->ip(),
                'login_time'=>time(),'create_time'=>time(),'update_time'=>time()
                ];
            $model=new Admin();
            $res=$model->addData($data);
            if($res){
                $this->success("添加成功","administrator");
            }else{
                $this->error("添加失败",'addAdministrator');
            }
        }
    }
    public  function editeAdministrator(){
        $id = input('admin_id');
        if ($this->request->isGet()) {
            $where = [
                'admin_id' => $id
            ];
            $node = $this->admin->getOne($where);
            $this->assign("admin", $node);
            return $this->fetch();
        } else {
            $data = [
                'username' => input('username'),
                'status' => input('status')
            ];
            $where = [
                'admin_id' => $id
            ];
            $res = $this->admin->saveDate($data, $where);
            if ($res) {
                $this->success('编辑成功', 'administrator');
            } else {
                $this->error('编辑失败', 'editeAdministrator');
            }
        }
    }
    //删除管理员
    public function delAdministrator()
    {
        $ids = input('admin_id/a', []);
        foreach ($ids as $id) {
            $where = [
                'admin_id' => $id
            ];
            $res = $this->admin->delData($where);
        }
//如果是单行删除，以json 形式返回数据
        if (input('is_row')) {
            if ($res) {
                return json([
                    'status' => 1,
                    'msg' => '删除成功'
                ]);
            } else {
                return json([
                    'status' => 0,
                    'msg' => '删除失败'
                ]);
            }
        } else {
            //如果是多行输出，以跳转的形式返回
            if ($res) {
                $this->success('删除成功', 'administrator');
            } else {
                $this->error('删除失败', 'administrator');
            }
        }
    }
    /**
     * 展示角色列表
     */
    public function role(){
        $data=$this->role->getAll();
        $this->assign("roles",$data);
        return $this->fetch();
    }
    //删除角色
    public function delRole()
    {
        $id = input('id');
        $where = [
            'id' => $id
        ];
        $res = $this->role->delData($where);
        if ($res) {
            return json([
                'status' => 1,
                'msg' => '删除成功'
            ]);
        } else {
            return json([
                'status' => 0,
                'msg' => '删除失败'
            ]);
        }
    }
    /**
     * 添加角色
     */
    public function addRole(){
        if($this->request->isGet()){
            return $this->fetch();
        }else{
            $data=['name'=>input('name'),
                'remark'=>input('remark'),
                'status'=>input('status')
                ];
            $res=$this->role->addData($data);
            if($res){
                $this->success('角色添加成功','role');
            }else{
                $this->error('角色添加失败','addrole');
            }
        }
    }
    /**
     * 编辑角色信息
     */
    public function editeRole(){
        $id=input('id');
        if($this->request->isGet()){
            $role=$this->role->getOne(['id'=>$id]);
            $this->assign('data',$role);
            return $this->fetch();
        }else{
            $data=['name'=>input('name'),'remark'=>input('remark'),'status'=>input('status')];
            $where=['id'=>$id];
            $res=$this->role->saveDate($data,$where);
            if($res){
                $this->success('角色编辑成功',"role");
            }else{
                $this->error('角色编辑失败','editeRole');
            }
        }
    }
    /**
     * 添加规则
     */
    public function Rule()
    {
        $data = $this->Rule->getAll();
        $res = node_merge($data);

        $this->assign('ress', $res);
        return $this->fetch();

    }
    /**
     *tianjia 添加规则
     */
    public function addRule(){
        if($this->request->isGet()){
            $id=input('id',0);
            $parent_rule=$this->Rule->getAll(['pid'=>0]);
            $this->assign("id",$id);
            $this->assign('parent_tule',$parent_rule);
            return $this->fetch();
        }else{
            $data=$this->request->post();
            $data['level']=$data['pid']==0?1:2;
            $res=$this->Rule->addData($data);
            if($res){
                $this->success("添加规则成功",'rule');
            }else{
                $this->error("添加失败","addrule");
            }
        }
    }
    //编辑规则
    public function editeRule(){
        if($this->request->isGet()){
            //获取传递过来的id
            $id=input('id',0);
            //根据规则id查询规则的详情信息
            $rule=$this->Rule->getOne(['id'=>$id]);
            //查询所有的控制器规则也就是父规则
            $parent_tule=$this->Rule->getAll(['pid'=>0]);
            $this->assign("parent_rule",$parent_tule);
            $this->assign("data",$rule);
            //分配过去的变量时当前规则的pid字段的值
            $this->assign("id",$rule['pid']);
            return $this->fetch();
        }else{
            $data=$this->request->post();
            $data['status']='hello';
            $id=$data['id'];

            //从数据中删除id元素
            unset($data['id']);
            $res=$this->Rule->saveDate($data,['id'=>$id]);
            if($res>0){
                $this->success("编辑规则成功",'rule');
            }else{
                $this->error('没有更新任何数据',"editerule?id=$id");
            }
        }
    }
    //删除规则
    public function delRule(){
        $id=input('id');
        $res=$this->Rule->delData(['id'=>$id]);
        if($res){
            return json(['status'=>1,'msg'=>'删除成功']);
        }else{
            return json(['status'=>0,'msg'=>'删除失败']);
        }
    }
    //重置密码
    public function resetPwd()
    {

        if ($this->request->isGet()) {
            $admin_id = input('admin_id');
            $this->assign('admin_id', $admin_id);
            return $this->fetch();
        } else {
            $admin_id = input('admin_id');
            $password = input('password');
            //根据管理员id获取管理员的salt 值
            $admin = $this->admin->getOne([
                'admin_id' => $admin_id
            ]);
            $data = [
                'password' => md5(md5($password) . $admin['salt'])
            ];
            $where = [
                'admin_id' => $admin_id
            ];
            $res = $this->admin->save($data, $where);
            if ($res) {
                $this->success('重置密码成功', 'rule');
            } else {
                $this->error('重置密码失败', "editerule?id=$admin_id");
            }
        }
    }
    public function access(){
        if($this->request->isGet()){
            //获取角色id
            $id=input('id');
            //查询角色信息
            $role=$this->role->getOne(['id'=>$id]);
            $this->assign("role",$role);

            //查询出所有的规则信息
            $data=$this->Rule->getAll();
            $res=node_merge($data);

            //查询出当前角色拥有的规则
            $has_rules=$this->role_rule->getAll(["role_id"=>$id],'rule_id');
            //遍历二维数组，转换成一位数组
            $has_rules_one=[];
            foreach($has_rules as $rule){
                $has_rules_one[]=$rule['rule_id'];
            }
            $this->assign("rules",$res);
            $this->assign("has_rules_one",$has_rules_one);

            return $this->fetch();
        }else{
            $data=$this->request->post();
            //先删除角色以前拥有的权限
            $this->role_rule->delData(['role_id'=>$data['id']]);
            //再为角色插入新的勾选的权限
            foreach ($data['rule']as$rule){
                $newdata=['role_id'=>$data['id'],"rule_id"=>$rule];
                $res=$this->role_rule->insert($newdata);
            }if($res){
                $this->success("权限分配成功","role");
            }else{
                $this->error("权限分配失败","access");
            }
        }
    }
    public function distributionRole()
    {
        if ($this->request->isGet()) {
            $admin_id = input('admin_id');
            //查询管理员信息
            $admin = $this->admin->getOne(['admin_id' => $admin_id]);

            //查询所有角色
            $roles = $this->role->getAll();
            $this->assign('roles', $roles);
            //查询出当前角色的拥有的角色
            $has_rules=$this->admin_role->getAll(['admin_id'=>$admin_id],'role_id');
            $has_rules_one=[];
            foreach ($has_rules as $rule){
                $has_rules_one[]=$rule['role_id'];
            }
            $this->assign("has_rules_one",$has_rules_one);
            $this->assign('admin', $admin);
            return $this->fetch();
        } else {
            $data = $this->request->post();
            //先删除用户已经拥有的角色
            $this->admin_role->delData(['admin_id' => $data['admin_id']]);
            foreach ($data['roles'] as $role) {
                $add_data = [
                    'admin_id' => $data['admin_id'],
                    'role_id' => $role
                ];
                $res=$this->admin_role->addData($add_data);
            }
            if ($res) {
                $this->success('角色分配成功', 'administrator');
            } else {
                $this->error('角色分配失败', "distributionRole");
            }
        }
    }
}